package com.egdigital.allzic.data.json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.egdigital.allzic.data.object.Location;

public class JsonParserLocation {

	// log
	private static final String			TAG					= JsonParserLocation.class.getSimpleName();
	// data
	private static final String			TAG_ARRAY			= "postalCodes";
	private static final String			TAG_COUNTRY			= "countryCode";
	private static final String			TAG_CITY			= "postalCode";
	private static final String			TAG_DEPARTMENT		= "adminCode2";
	private RequestQueue				mRequestQueue;
	private static JsonParserLocation	mJsonParser;
	private Location					mLocation;
	private JSONArray					mJsonArrayCategory	= null;
	private JsonCallBack				mJsonCallback;

	public static JsonParserLocation getInstance() {
		if (mJsonParser == null) {
			mJsonParser = new JsonParserLocation();
		}
		return mJsonParser;
	}

	public void initAndStartRequestQueue() {
		mRequestQueue = VolleyManager.getRequestQueue();
		mRequestQueue.start();
	}

	public void stopRequestQueue() {
		mRequestQueue.stop();
	}

	public void extractJsonObjectData(String url) {
		JsonObjectRequest request = new JsonObjectRequest(url, null, createMyReqSuccessListener(), createMyReqErrorListener());
		request.setTag(this);
		mRequestQueue.add(request);
	}

	protected Response.Listener<JSONObject> createMyReqSuccessListener() {
		return new Response.Listener<JSONObject>() {

			public void onResponse(JSONObject jsonObject) {
				List<Location> listLocation = new ArrayList<Location>();
				try {
					mJsonArrayCategory = jsonObject.getJSONArray(TAG_ARRAY);
					for (int i = 0; i < mJsonArrayCategory.length(); i++) {
						mJsonCallback.downloadPercent(((i + 1) * 100) / mJsonArrayCategory.length());
						JSONObject jsonLocation = mJsonArrayCategory.getJSONObject(i);
						mLocation = new Location(jsonLocation.getString(TAG_CITY), jsonLocation.getString(TAG_DEPARTMENT), jsonLocation.getString(TAG_COUNTRY));
						listLocation.add(mLocation);
					}
				} catch (Exception ex) {
					Log.e(TAG, "", ex);
				}
				mJsonCallback.downloadCompleted(listLocation);
			}
		};
	}

	protected Response.ErrorListener createMyReqErrorListener() {
		return new Response.ErrorListener() {

			public void onErrorResponse(VolleyError error) {
				mJsonCallback.downloadEndedWithError(error);
			}
		};
	}

	public void setJsonCallBack(JsonCallBack callback) {
		mJsonCallback = callback;
	}
}